package com.jxl.wechat.handler;

import com.jxl.wechat.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 处理Text
 */
@Component
public class WeChatTextHandler  implements WeChatMsgHandler{

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WeChatMsgTypeEnums getMsgType() {
        return WeChatMsgTypeEnums.TEXT;
    }

    @Override
    public String deal(Map<String, String> map) {
        String fromUserName = map.get("FromUserName");
        String toUserName = map.get("ToUserName");
        //生成随机验证码
        Random random = new Random();
        int num = random.nextInt(1000);
        String numContent ="";
        String content = map.get("Content");
        if (!KEY_WORD.equals(content)) {
            numContent+= "请输入正确指令，例如：验证码";
        }else {
            //redis进行储存
            String s = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
            redisUtil.setNx(s,fromUserName,5L, TimeUnit.MINUTES);
            numContent+= "您当前的验证码是：" + num + "！ 5分钟内有效";
        }
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return replyContent;

    }
}
